<!-- 
MIT License

Copyright (c) 2019, 2020 Steve-Mcl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. 
-->

<script type="text/javascript">
  function setupTypedInput(varName, types, def) {
    let varSel = '#node-input-' + varName;
    let typeSel = varSel + 'Type';
    let varVal = this[varName];
    let typeVal = this[varName + 'Type'];

    if (typeVal == null || typeVal === 'none') {
      typeVal = def;
    } else if (typeVal === 'string') {
      typeVal = "str";
    } else if (typeVal === 'number') {
      typeVal = "num";
    }
    $(typeSel).val(typeVal);
    $(varSel).typedInput({
      default: def,
      typeField: $(typeSel),
      types: types
    });
    $(varSel).typedInput('type', typeVal);
  }
  RED.nodes.registerType('MC Write', {
    category: 'MITSUBISHI',
    color: '#0090d4',
    defaults: {
      name: { value: "" },
      topic: { value: "" },
      connection: { type: "MC Protocol Connection", required: true },
      data: { value: "" },
      address: { value: "", validate: RED.validators.typedInput("addressType") },
      addressType: { value: "str" },
      data: { value: "", validate: RED.validators.typedInput("dataType") },
      dataType: { value: "str" },
      errorHandling: { value: "throw" },
      outputs: { value: 1 }
    },
    inputs: 1,
    outputs: 1,
    inputLabels: "Trigger request",
    outputLabels: "Write result",
    align: "right",
    icon: "write.png",
    label: function () {
      return this.name || "MC Write";
    },
    oneditprepare: function () {
      var sti = setupTypedInput.bind(this);
      sti('address', ['msg', 'flow', 'global', 'str', 'env'], 'str');//addr
      sti('data', ['msg', 'flow', 'global','num','str', {
        value: 'csv',
        label: 'csv',
        icon: "red/images/typedInput/09.png"
      },], 'num');
    }, 
    oneditsave: function () {
      var errH = $("#node-input-errorHandling").val();
      this.outputs = errH === "output2" ? 2 : 1;//1 output pins if throw or msg.error, 2 outputs if errors to go to seperate output pin
    }
  });
</script>

<style>
  .mc-protocol-form > .form-row > label {
    width: 120px !important;
  }
</style>

<script type="text/html" data-template-name="MC Write">
  <div class="mc-protocol-form">
    <div class="form-row">
      <label for="node-input-name"><i class="icon-tag"></i> <span data-i18n="write.label.name"> Name</span></label>
      <input type="text" id="node-input-name" placeholder="Name">
    </div>
    <div class="form-row">
      <label for="node-input-connection"><i class="icon-globe"></i><span data-i18n="write.label.connection"> Connection</span></label>
      <input type="text" id="node-input-connection">
    </div>
    <div class="form-row">
      <label for="node-input-address"><i class="fa fa-envelope"></i><span data-i18n="ab-df1-read.label.address"> Address</span></label>
      <input type="hidden" id="node-input-addressType">
      <input style="width: 70%" type="text" id="node-input-address" placeholder="D0">
    </div>
    <div class="form-row">
      <label for="node-input-data"><i class="fa fa-table"></i> <span data-i18n="write.label.data"> Data</span></label>
      <input type="hidden" id="node-input-dataType">
      <input style="width: 70%" type="text" id="node-input-data" >
    </div>
    <div class="form-row">
      <label for="node-input-errorHandling"><i class="fa fa-exclamation"></i><span data-i18n="ab-df1-read.label.errors"> Errors</span></label>
      <select style="width: 70%" id="node-input-errorHandling">
        <option value="throw">Throw (default)</option>
        <option value="msg">Output to msg.error</option>
        <option value="output2">Send to seperate output</option>
      </select>
    </div> 
  </div>
</script>

<script type="text/html" data-help-name="MC Write">
  <p>Write data to an MITSUBISHI PLC using mcprotocol protocol</p>
  <h3>Inputs</h3>
  <dl class="message-properties">
    <dt class="required">Connection<span class="property-type">DF1 Connection</span></dt>
    <dd>The PLC connection</dd>
    <dt class="required">Address<span class="property-type">number | string | payload</span></dt>
    <dd>PLC Memory Address</dd>
    <dt class="required">Data<span class="property-type">Array&lt;number&gt; | number | string | payload </span></dt>
    <dd>Data to be written to PLC starting at specified address.</dd>
    <p><i>INFO: To open / close the MC Protocol connection, send boolean <code>true</code> in <code>msg.connect</code> , <code>msg.disconnect</code> or <code>msg.reinitialize</code>.  Alternatively, send string <code>connect</code>, <code>disconnect</code> or <code>reinitialize</code> in <code>msg.topic</code> to the any mc read / mc write node.</i></p>
  </dl>
  <h3>Outputs</h3>
  <dl class="message-properties">
    <dt>payload <span class="property-type">boolean</span></dt>
    <dd>Payload will be <code>true</code> if successful</dd>
    <dt>mcWriteDetails <span class="property-type">object</span></dt>
    <dd><code>msg.mcWriteDetails</code> will contain properties like <code>isGood</code>, <code>quality</code>, <code>TAG</code> etc.  The user should inspect these to determine if the PLC write command was unsuccessful.</dd>
    <dd>Use a debug node to inspect the object</dd>
  </dl>
  <h3>Details</h3>
  <p>
    If an error occurs the output of this node may still be triggered. 
    In this case, the payload maybe invalid but the <code>mcWriteDetails</code> will contain additional information about the problem.
  </p>
  <p>Address format [DS] DEV [DT] DN [.BIT] [,CNT] [:OPTS]...  
    <ol>
      <li>[1] DS	 - {string} Digit specifier (e.g. K4) [optional]</li>
      <li>[2] DEV  - {string} Device (Y|X|D|F|W|B|R|etc)</li>
      <li>[3] DT 	 - {string} Data type (REAL|FLOAT|STR|WORD|DWORD|DINT|UINT) [optional]</li>
      <li>[4] DN 	 - {int} Device number</li>
      <li>[5] BIT  - {int} Bit number [optional]</li>
      <li>[6] CNT  - {int} Count of items [optional]</li>
      <li>[7] OPTS - {JSON} Options for specifying network and station e.g. {N:2,S:3} would attempt to route the message to station 3 on network 2 [optional]</li>
    </ol>
    <i>Notes...<br>DS and DT should not be used together. <br>if CNT is omitted, then <code>1</code> is assumed. <br>DN may be DEC or HEX depending on the notation of the Device e.g. YA, X1E, WBA4, B3D   </i> 
  </p>
  <p>data must match the address style e.g...
    <table>
      <tr>
        <td>Address Example</td>
        <td>Expected Type</td>
        <td>Notes</td>
        </tr>
      <tr>
        <td>K4Y0</td>
        <td>int</td>
        <td>−32,768 to 32,767</td>
        </tr>
      <tr>
        <td>DSTR0,10</td>
        <td>string</td>
        <td>Upto 10 chars long</td>
        </tr>
      <tr>
        <td>DUINT0,10</td>
        <td>UINT[10]</td>
        <td>10 WD array containing values 0 to 65535</td>
        </tr>
    </table>
  </p>
</script>